import { h, App, Directive, createVNode, render, DirectiveBinding, ComponentPublicInstance } from 'vue';
import Contextmenu from '@/components/contextmenu/src/contextmenu.vue';
Contextmenu.install = (app: App): void => {
  app.component(Contextmenu.name, Contextmenu);
};
let contextmenuCtx: any;

export const CustomMouseMenu = (options: any): any => {
  if (options.isMine) {
    var el1 = options.mouse.currentTarget;
    var el2 = options.mouse.target;
    if (el1 != el2) {
      return;
    }
  }
  options.mouse.stopPropagation();
  options.mouse.preventDefault();
  const className = '__mouse__menu__container';
  let container: HTMLElement;
  if (document.querySelector(`.${className}`)) {
    container = document.querySelector(`.${className}`) as HTMLElement;
  } else {
    container = document.createElement('div');
    container.setAttribute('class', className);
  }
  const vm = h(Contextmenu, options);
  render(vm, container);
  document.body.appendChild(container);
  return vm.component?.proxy as ComponentPublicInstance<typeof Contextmenu>;
};
type ContextMenuListenFn = (e: MouseEvent) => void;
let contextMenuEvent: ContextMenuListenFn;
const ContextmenuDirective: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding;
    if (value.menus.length <= 0) return;
    contextMenuEvent = (e: MouseEvent) => {
      if (typeof value.disabled === 'function' && value.disabled(value.params)) return;
      contextmenuCtx = CustomMouseMenu({
        el,
        mouse: e,
        menus: value.menus,
        isMine: value.isMine,
      });
      if (contextmenuCtx) contextmenuCtx.$root.show();
    };
    el.removeEventListener('contextmenu', contextMenuEvent);
    el.addEventListener('contextmenu', contextMenuEvent);
  },
  unmounted(el: HTMLElement) {
    el.removeEventListener('contextmenu', contextMenuEvent);
  },
};
export default ContextmenuDirective;
